import { Component, Input, OnInit, ElementRef, OnDestroy, NgZone, ChangeDetectorRef } from '@angular/core';
import { PopupTipConfig, PopupTipType } from './popup-tip.model';
import { animate, style, transition, trigger } from '@angular/animations';

@Component({
  selector: 'ns-popup-tip',
  templateUrl: './popup-tip.component.html',
  styleUrls: ['./popup-tip.component.css'],
  animations: [
    trigger('popupAnimation', [
      transition(':enter', [
        style({ opacity: 0, transform: 'translateY(10px)' }),
        animate('200ms ease-out', style({ opacity: 1, transform: 'translateY(0)' }))
      ]),
      transition(':leave', [
        animate('200ms ease-in', style({ opacity: 0, transform: 'translateY(-10px)' }))
      ])
    ])
  ]
})
export class CheesePopupTipComponent implements OnInit, OnDestroy {
  @Input() config: PopupTipConfig = {
    message: '',
    type: 'info',
    duration: 2000,
    closable: false,
    position: 'top'
  };

  @Input() targetElement?: ElementRef;

  visible = false;
  private timeoutId?: number;

  constructor(
    private el: ElementRef,
    private zone: NgZone,
    private cdr: ChangeDetectorRef
  ) {}

  ngOnInit(): void {
    this.positionElement();
  }

  ngOnDestroy(): void {
    this.clearTimeout();
  }

  show(): void {
    this.zone.run(() => {
      this.visible = true;
      this.cdr.detectChanges();
      this.positionElement();
      
      if (this.config.duration && this.config.duration > 0) {
        this.clearTimeout();
        this.timeoutId = window.setTimeout(() => {
          this.hide();
        }, this.config.duration);
      }
    });
  }

  hide(): void {
    this.zone.run(() => {
      this.visible = false;
      this.cdr.detectChanges();
    });
  }

  private clearTimeout(): void {
    if (this.timeoutId) {
      clearTimeout(this.timeoutId);
      this.timeoutId = undefined;
    }
  }

  private positionElement(): void {
    if (!this.targetElement || !this.visible) return;

    const targetRect = this.targetElement.nativeElement.getBoundingClientRect();
    const tipElement = this.el.nativeElement;
    
    // 确保提示元素已经渲染
    setTimeout(() => {
      const tipRect = tipElement.getBoundingClientRect();
      
      let top = 0;
      let left = 0;
      
      switch (this.config.position) {
        case 'top':
          top = targetRect.top - tipRect.height - 10;
          left = targetRect.left + (targetRect.width - tipRect.width) / 2;
          break;
        case 'bottom':
          top = targetRect.bottom + 10;
          left = targetRect.left + (targetRect.width - tipRect.width) / 2;
          break;
        case 'left':
          top = targetRect.top + (targetRect.height - tipRect.height) / 2;
          left = targetRect.left - tipRect.width - 10;
          break;
        case 'right':
          top = targetRect.top + (targetRect.height - tipRect.height) / 2;
          left = targetRect.right + 10;
          break;
        default:
          top = targetRect.top - tipRect.height - 10;
          left = targetRect.left + (targetRect.width - tipRect.width) / 2;
      }
      
      // 确保提示不会超出视口
      const viewportWidth = window.innerWidth;
      const viewportHeight = window.innerHeight;
      
      if (left < 0) left = 0;
      if (left + tipRect.width > viewportWidth) left = viewportWidth - tipRect.width;
      if (top < 0) top = 0;
      if (top + tipRect.height > viewportHeight) top = viewportHeight - tipRect.height;
      
      // 设置位置
      tipElement.style.top = `${top}px`;
      tipElement.style.left = `${left}px`;
    }, 0);
  }

  getIconClass(): string {
    return `popup-tip-icon-${this.config.type || 'info'}`;
  }

  getIcon(): string {
    switch (this.config.type) {
      case 'success':
        return '✓';
      case 'error':
        return '✗';
      case 'warning':
        return '⚠';
      case 'info':
      default:
        return 'ℹ';
    }
  }
}